<?php

namespace App\Helpers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Helpers
{
    //1.1日志
    public static function log($msg,$type='laravel')
    {
        $msg = is_string($msg)?$msg:json_encode($msg);
        try{
            $log_path = storage_path('logs/').$type.'.log';
            if (file_exists($log_path) && filesize($log_path) > 20*1048576) {
                $bool =  rename($log_path,storage_path('logs/').$type.'_'.date('Ymd').'.log');
                if(!$bool){
                    Log::error('rename logs/'.$type.'.log fail');
                }
            }
            $f = fopen($log_path,'a') or die("Unable to open file!");
            $msg = '['.date('Y-m-d H:i:s').'] '.$msg."\n";
            fwrite($f,$msg);
            fclose($f);
        }catch (\Exception $e){
            Log::error($type.'.log file write fail');
        }
    }
    //1.2保存临时json文件
    public static function saveTempJson($data,$type)
    {
        try{
            @mkdir(storage_path('json/'));
            $log_path = storage_path('json/').$type.'.json';
            $f = fopen($log_path,'w') or die("Unable to open file!");
            fwrite($f,json_encode($data));
            fclose($f);
        }catch (\Exception $e){
            Log::error($e->getMessage());
        }

    }
    //1.3获取临时json文件内容
    public static function getTempJson($type,$array=false)
    {
        $json_path = storage_path('json/').$type.'.json';
        if(file_exists($json_path)) {
            if ($array){
                return json_decode(file_get_contents($json_path),true);
            }
            return json_decode(file_get_contents($json_path));
        }
        return false;
    }

    //2.获取post请求响应
    public static function get_post_respond($url,$post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }

    //5.0创建不同类型的流水号
    public static function createSerialNumber($table,$field='number',$type=0,$date=false)
    {
        //流水号默认日期为今天
        if($date) $str = date('Ymd',strtotime($date)) . $type;
        else $str = date('Ymd') . $type;

        return self::getSerialNumber($str,mt_rand(0,9999999),$table,$field);
    }
    //5.1获取流水号
    public static function getSerialNumber($str,$number,$table,$field)
    {
        $count = DB::table($table)
            ->where($field,'=',$str.sprintf("%07d",$number))
            ->count();
        if( $count>0) {
            $newNumber = $number+1;
            if($newNumber>9999999) $newNumber = mt_rand(0,9999999);
            return self::getSerialNumber($str,$newNumber,$table,$field);
        } else {
            return $str.sprintf("%07d",$number);
        }
    }

    //5.0创建不同类型的编码
    public static function createSerialCode($table,$field='number',$type=1000)
    {
        return self::getSerialCode($type,mt_rand(0,9999999),$table,$field);
    }
    //5.1获取不同类型的编码
    public static function getSerialCode($str,$number,$table,$field)
    {
        $count = DB::table($table)
            ->where($field,'=',$str.sprintf("%09d",$number))
            ->count();
        if( $count>0) {
            $newNumber = $number+1;
            if($newNumber>999999999) $newNumber = mt_rand(0,999999999);
            return self::getSerialCode($str,$newNumber,$table,$field);
        } else {
            return $str.sprintf("%09d",$number);
        }
    }

    //5.2创建不同类型的编码
    public static function createSerial($table,$field='number',$prefix)
    {
        return self::getSerial($prefix,mt_rand(0,999999999),$table,$field);
    }
    //5.3获取不同类型的编码
    public static function getSerial($prefix,$number,$table,$field)
    {
        $count = DB::table($table)
            ->where($field,'=',$prefix.sprintf("%09d",$number))
            ->count();
        if( $count>0) {
            $newNumber = $number+1;
            if($newNumber>999999999) $newNumber = mt_rand(0,999999999);
            return self::getSerialNumber($prefix,$newNumber,$table,$field);
        } else {
            return $prefix.sprintf("%09d",$number);
        }
    }

    //6.1酒庄编码10001
    public static function createChateauCode($date=false)
    {
        return self::createSerialCode('wine_chateau','chateauCode',10001);
    }
    //6.2酒编码10001
    public static function createWineProductCode($date=false)
    {
        return self::createSerialCode('wine_product','code',20001);
    }

    //退款订单号
    public static function createOrderRefundOutTradeNo($prefix=false)
    {
        if (!$prefix) {
            $prefix = substr(date('Ymd'),2).'30';
        }
        return self::createSerialCode('orders','out_trade_no',$prefix);
    }

    //交易订单号
    public static function createOrderOutTradeNo($type,$prefix=false)
    {
        if (!$prefix) {
            $prefix = substr(date('Ymd'),2);
            $prefix .= $type=="gift"?"20":"10";
        }
        return self::createSerialCode('orders','out_trade_no',$prefix);
     }

     //优惠券编码
    public static function createCouponCode()
    {
        return self::createSerialCode('wine_coupons','code',30001);
    }


    //格式化值
    public static function translateVal($key,$value,$reverse = false)
    {
        if ($config = \Config::get("translate.".$key))
        {
            if($reverse ) {
                $key =  array_search($value,$config);
                return $key!==false ? $key : $value;
            } else {
                return isset($config[$value]) ? $config[$value] : $value;
            }
        }

        return $value;
    }

    //10.1对比输出
    public static function contrast($now,$original,$except)
    {
        $attr = [];
        foreach ($now as $k=>$v) {
            if(!in_array($k,$except) && isset($original[$k]) && $original[$k] != $v) {
                $attr['before'][$k] = $original[$k];
                $attr['after'][$k] = $v;
            }
        }
        return $attr;
    }
    //10.2
    public static function contrastTranslate($key,$now,$original,$except=['created_at','updated_at'])
    {
        $before = ' [更新前] ';
        $after  = ' [更新后] ';
        $t = \Config::get('translate.'.$key);
        foreach ($now as $k=>$v) {
            if(!in_array($k,$except) && isset($original[$k]) && $original[$k] != $v) {
                $key = isset($t[$k])?$t[$k]:$k;
                $before .= $key.':'.self::translateVal($k,$original[$k]).' ';
                $after .= $key.':'.self::translateVal($k,$v) .' ';
            }
        }
        return $before.$after;
    }

    public static function now()
    {
        return date('Y-m-d H:i:s');
    }

    public static function SYSJ($unixEndTime)
    {
        if ($unixEndTime <= time()) { // 如果过了活动终止日期
            return '0天0时0分';
        }

        // 使用当前日期时间到活动截至日期时间的毫秒数来计算剩余天时分
        $time = $unixEndTime - time();

        $d = 0;
        if ($time >= 86400) { // 如果大于1天
            $d= (int)($time / 86400);
            $time = $time % 86400; // 计算天后剩余的毫秒数
        }

        $h = 0;
        if ($time >= 3600) { // 如果大于1小时
            $h = (int)($time / 3600);
            $time = $time % 3600; // 计算小时后剩余的毫秒数
        }

        $m = (int)($time / 60); // 剩下的毫秒数都算作分

        if ($d>0) {
            return $d.'天'.$h.'时';
        }

        if ($h>0) {
            return $h.'时'.$m.'分';
        }
        if ($m>0) {
            return $m.'分';
        }
    }
}
